package top.liujiachen.springboot.shiro.controller;

import cn.hutool.crypto.KeyUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.signers.AlgorithmUtil;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import top.liujiachen.springboot.shiro.vo.Result;
import top.liujiachen.springboot.shiro.vo.SuccessResult;

@RestController
public class LoginController {

    private Logger log = LoggerFactory.getLogger(getClass());

    public final String SIGNER_ID = "rs256";
    public final JWTSigner SIGNER = JWTSignerUtil.createSigner(SIGNER_ID,
            // 随机生成密钥对，此处用户可自行读取`KeyPair`、公钥或私钥生成`JWTSigner`
            KeyUtil.generateKeyPair(AlgorithmUtil.getAlgorithm(SIGNER_ID)));

    @GetMapping("/login")
    public Result login(String username, String password) {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return Result.init(100, "请输入用户名和密码！");
        }
        //用户认证信息
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, SecureUtil.md5(password));
        try {
            //进行验证，这里可以捕获异常，然后返回对应信息
            subject.login(usernamePasswordToken);
//            subject.checkRole("admin");
//            subject.checkPermissions("query", "add");
        } catch (UnknownAccountException e) {
            log.error("用户名不存在！", e);
            return Result.init(101, "用户名不存在！");
        } catch (AuthenticationException e) {
            log.error("账号或密码错误！", e);
            return Result.init(102, "账号或密码错误！");
        } catch (AuthorizationException e) {
            log.error("没有权限！", e);
            return Result.init(200, "没有权限！");
        }
        try {
            System.err.println(subject.getSession().getId());
        }catch (Exception e) {
            e.printStackTrace();
        }

        String token = JWT.create()
                .setPayload("sub", "1234567890")
                .setPayload("name", "looly")
                .setPayload("admin", true)
                .setSigner(SIGNER)
                .sign();
        return SuccessResult.init(0, "登录成功", token);
    }

    @RequiresRoles("admin")
    @GetMapping("/admin")
    public String admin() {
        return "admin success!";
    }

    @RequiresPermissions("user:query")
    @GetMapping("/index")
    public String index() {
        return "index success!";
    }

    @RequiresPermissions("user:add")
    @GetMapping("/add")
    public String add() {
        return "add success!";
    }

}
